package vn.codespot.hms;

import com.zooz.android.lib.CheckoutActivity;
import com.zooz.android.lib.model.ZooZInvoice;

import vn.codespot.hms.model.response.StatusResponseModel;
import vn.codespot.hms.slidingmenu.SlidingActivityBase;
import vn.codespot.hms.slidingmenu.SlidingActivityHelper;
import vn.codespot.hms.task.CheckStatusTask;
import vn.codespot.hms.task.ITaskListener;
import vn.codespot.VisaVietNamAndroid.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class CheckStatusActivity extends AbstractActivity implements SlidingActivityBase {

	private final int ZOOZ_ID = 3333;
	
    private SlidingActivityHelper mHelper;

    private View mLyOne;

    private View mLyTwo;

    private Button mLyOneCheckBtn;

    private EditText mLyOneTrackingId;

    private TextView mLyTwoTrackingId;

    private TextView mLyTwoStatus;
    
    private TextView mLyTwoFeeTotal;

    private static Double total_fee; 
    
    @SuppressWarnings("unused")
    private boolean mIsInOne;

    private boolean mIsInTwo;

    // private Button mLyTwoBtnBack;

    private Button mLyTwoBtnSecureCheckOut;

    private String[] mStatusCodes;

    private ImageButton mBtnShowMenu;

    private ImageButton mBtnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mHelper = new SlidingActivityHelper(this);
        setMenu(mHelper);
        mHelper.onCreate(savedInstanceState);
        View v_behide = getLayoutInflater().inflate(R.layout.menu_layout, null);
        setBehindContentView(v_behide);
        View v = getLayoutInflater().inflate(R.layout.check_status_layout, null);
        setContentView(v);
        setBehindOffset(100);
        setSlidingActionBarEnabled(true);
        mBtnShowMenu = (ImageButton) v.findViewById(R.id.btnShowMenu);
        mBtnBack = (ImageButton) v.findViewById(R.id.btn_back);
        final RadioGroup radGroupMenu = (RadioGroup) v_behide.findViewById(R.id.radGroupMenu);
        final RadioButton radCheckStatus = (RadioButton) v_behide.findViewById(R.id.radCheckStatus);
        radCheckStatus.setChecked(true);
        mBtnShowMenu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	hideKeyBoard(v);
                toggle();
            }
        });

        radGroupMenu.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (mHelper.isShowMenu()) {
                    Intent intent = null;
                    toggle();
                    switch (checkedId) {
                    case R.id.radRegister:
                        intent = new Intent(CheckStatusActivity.this, RegisterActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radCheckFees:
                        intent = new Intent(CheckStatusActivity.this, CheckFeesActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radCheckStatus:
                        break;
                    case R.id.radContactUs:
                        intent = new Intent(CheckStatusActivity.this, ContactUsActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radHowToUse:
                        intent = new Intent(CheckStatusActivity.this, HowToUseActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radSupport:
                        intent = new Intent(CheckStatusActivity.this, SupportActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radDisclaimer:
                        intent = new Intent(CheckStatusActivity.this, DisclaimerActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.radHistory:
                        intent = new Intent(CheckStatusActivity.this, HistoryActivity.class);
                        startActivity(intent);
                        break;
                    }
                    radGroupMenu.check(R.id.radCheckStatus);
                }
            }
        });

        mIsInOne = true;
        mIsInTwo = false;

        mStatusCodes = new String[] { this.getString(R.string.unknown), this.getString(R.string.waitingpayment),
                this.getString(R.string.processing), this.getString(R.string.completed), this.getString(R.string.refunded) };

        // mLyTwoBtnBack = (Button) findViewById(R.id.btn_back);
        mBtnBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View paramView) {
            	hideKeyBoard(paramView);
                if (isInTwo()) {
                    showOne();
                    togglePage(false, mLyOne, mLyTwo);
                }
            }
        });

        mLyOne = findViewById(R.id.lyOne);
        mLyTwo = findViewById(R.id.lyTwo);

        mLyOneTrackingId = (EditText) mLyOne.findViewById(R.id.trackingid);
        mLyOneCheckBtn = (Button) mLyOne.findViewById(R.id.btn_lyOne_check);
        mLyOneCheckBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	hideKeyBoard(v);
                boolean valid = validateLyOne();
                if (valid) {
                    showTwo();
                    togglePage(true, mLyOne, mLyTwo);
                    CheckStatusTask task = getCheckStatusTask();
                    task.execute();
                } else {
                    Toast.makeText(CheckStatusActivity.this, "Tracking ID must not be empty", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mLyTwoTrackingId = (TextView) mLyTwo.findViewById(R.id.lyTwo_TrackingId);
        mLyTwoStatus = (TextView) mLyTwo.findViewById(R.id.lyTwo_Status);
        mLyTwoFeeTotal = (TextView) mLyTwo.findViewById(R.id.lyTwo_TotalFee);

        mLyTwoBtnSecureCheckOut = (Button) mLyTwo.findViewById(R.id.btn_lyTwoSecureCheckout);
        mLyTwoBtnSecureCheckOut.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
            	ZooZInvoice invoice = new ZooZInvoice();
            	invoice.setInvoiceNumber(mLyTwoTrackingId.getText().toString().trim());
                Intent intent = new Intent(CheckStatusActivity.this, CheckoutActivity.class);
                intent.putExtra(CheckoutActivity.ZOOZ_APP_KEY, getString(R.string.ZOOZ_APP_KEY));
                 intent.putExtra(CheckoutActivity.ZOOZ_AMOUNT, total_fee);
                intent.putExtra(CheckoutActivity.ZOOZ_CURRENCY_CODE, getString(R.string.ZOOZ_CURRENT_CODE));
                intent.putExtra(CheckoutActivity.ZOOZ_IS_SANDBOX, true);
                intent.putExtra(CheckoutActivity.ZOOZ_INVOICE, invoice);
                startActivityForResult(intent, ZOOZ_ID);
            }
        });
    }

    private void hideKeyBoard(View v) {
//    	this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    	if (v != null && this.getApplicationContext() != null) {
    		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        	if(imm != null){
        	        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        	}
		}
    	
    	
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ZOOZ_ID) {
            switch (resultCode) {
            case Activity.RESULT_OK:
                // Transaction ID:
                // data.getStringExtra(CheckoutActivity.ZOOZ_TRANSACTION_ID)
                //showCompletePage(COMPLETE_SUCCESSFUL, data.getStringExtra(CheckoutActivity.ZOOZ_TRANSACTION_ID));
            	//showCompletePage(COMPLETE_SUCCESSFUL, HMSTrackingID);
            	Intent intent = new Intent(CheckStatusActivity.this, CheckStatusActivity.class);
            	startActivity(intent);
                break;
            case Activity.RESULT_CANCELED:
                if (data != null)
                    // ZOOZ error code:
                    // data.getIntExtra(CheckoutActivity.ZOOZ_ERROR_CODE, 0)
                    // ZOOZ error message:
                    // data.getStringExtra(CheckoutActivity.ZOOZ_ERROR_MSG)
                    Toast.makeText(CheckStatusActivity.this,
                            "Cannot complete payment with ZOOZ: " + data.getStringExtra(CheckoutActivity.ZOOZ_ERROR_MSG),
                            Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
            }
        }
    }
    
    
    private CheckStatusTask getCheckStatusTask() {
        ITaskListener listener = new ITaskListener() {
            @Override
            public void finish(Object... params) {
                try {
                    StatusResponseModel response = (StatusResponseModel) params[0];
                    int statusCode = response.getStatusCode();
                    if (StatusResponseModel.STATUS_INVALID_CODE == statusCode) {
                        Toast.makeText(CheckStatusActivity.this, response.getErrorMessage(), Toast.LENGTH_SHORT).show();
                        mLyTwoTrackingId.setText(mLyOneTrackingId.getText().toString().trim());
                        mLyTwoStatus.setText(mStatusCodes[0]);
                    } else {
                        mLyTwoTrackingId.setText(mLyOneTrackingId.getText().toString().trim());
                        mLyTwoStatus.setText(mStatusCodes[statusCode]);
                        mLyTwoFeeTotal.setText(response.getFeeTotal() + getString(R.string.unitDollar));
                        total_fee = Double.parseDouble(response.getFeeTotal());
                        if (StatusResponseModel.STATUS_WAITING_PAYMENT_CODE == statusCode) {
                            mLyTwoBtnSecureCheckOut.setVisibility(Button.VISIBLE);
                        } else {
                            mLyTwoBtnSecureCheckOut.setVisibility(Button.GONE);
                        }
                    }
                } catch (Exception ignore) {
                    mLyTwoTrackingId.setText(mLyOneTrackingId.getText().toString().trim());
                    mLyTwoStatus.setText(CheckStatusActivity.this.getString(R.string.unknown));
                }
            }
        };
        return new CheckStatusTask(CheckStatusActivity.this, listener, mLyOneTrackingId.getText().toString().trim());
    }

    private boolean isInTwo() {
        return mIsInTwo;
    }

    private boolean validateLyOne() {
        return !TextUtils.isEmpty(mLyOneTrackingId.getText().toString().trim());
    }

    private void togglePage(boolean next, View former, View later) {
        TranslateAnimation backward = null;
        TranslateAnimation forward = null;

        if (next) {
            backward = new TranslateAnimation(mLyOne.getWidth(), 0.0f, 0.0f, 0.0f);
            forward = new TranslateAnimation(0.0f, -mLyOne.getWidth(), 0.0f, 0.0f);
        } else {
            backward = new TranslateAnimation(0.0f, mLyOne.getWidth(), 0.0f, 0.0f);
            forward = new TranslateAnimation(-mLyOne.getWidth(), 0.0f, 0.0f, 0.0f);
        }

        backward.setDuration(300);
        backward.setInterpolator(new AccelerateInterpolator(1.0f));
        later.startAnimation(backward);

        forward.setDuration(300);
        forward.setInterpolator(new AccelerateInterpolator(1.0f));
        former.startAnimation(forward);
    }

    private void showOne() {
        // set visible menu
        mBtnShowMenu.setVisibility(View.VISIBLE);
        // Set visibilities for view
        mLyOne.setVisibility(LinearLayout.VISIBLE);
        mLyTwo.setVisibility(LinearLayout.GONE);

        // set flags
        mIsInOne = true;
        mIsInTwo = false;

        mBtnBack.setVisibility(View.GONE);
        mLyTwoBtnSecureCheckOut.setVisibility(Button.GONE);
    }

    private void showTwo() {
        mBtnShowMenu.setVisibility(View.GONE);
        // Set visibilities for view
        mLyTwo.setVisibility(LinearLayout.VISIBLE);
        mLyOne.setVisibility(LinearLayout.GONE);

        // set flags
        mIsInOne = false;
        mIsInTwo = true;

        mBtnBack.setVisibility(View.VISIBLE);
        mLyTwoBtnSecureCheckOut.setVisibility(Button.GONE);
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        return;
    }
}
